var dbc=require('./Datahandle');
var spider=require('./PageSpider');

var needspide=false;       //是否需要重新爬取数据
var needgetfromdb=true;     //是否需要从数据库拉取数据
var result="";


exports.init=function(){

    var cb=arguments[0]?arguments[0]:null;
    needspide=arguments[1]?arguments[1]:false;
    needgetfromdb=arguments[2]?arguments[2]:true;

    if(needspide){
        spider.spide_page(needgetfromdb,cb);
        needspide=false;
        // console.log("数据爬取成功");
    }else{
        console.log("不需要爬取新数据");
        if(needgetfromdb){
            if(cb){
                cb();
            }
        }else{
            console.log("不需要从数据库中拉取数据");
        }
    }

    console.log("初始化分析器");
};

exports.analysis_sameCompany_price=function(company){
    return(function(){

        var sql="SELECT DISTINCT priceBase , departureDate , arlineCompanyShortName , orgCityName,dstCityName , discount FROM flightinfo WHERE arlineCompanyShortName=\'";
        sql+=company;
        sql+="\' OR arlineCompany=\'";
        sql+=company;
        sql+="\' ORDER BY departureDate,discount";

        // console.log(sql);
        dbc.sql(sql,function(res){
            console.log(res);
            for(var result in res){
                contexts[contexts.length]={text:JSON.stringify(res[result].RowDataPacket)}
            }

        });
    })
};
exports.analysis_sameDate_price=function(date){
    return(function(){

        var sql="SELECT priceBase , departureDate , arlineCompanyShortName , orgCityName,dstCityName , discount FROM flightinfo WHERE departureDate like \'";
        sql+=date;
        sql+="\'";

        // console.log(sql);

        dbc.sql(sql,function(res){
            console.log(res);
            for(var result in res){
                contexts[contexts.length]={text:JSON.stringify(res[result].RowDataPacket)}
            }

        });
    })
};

exports.analysis_sameRoute_price=function(){
    return(function(){
        var sql="SELECT DISTINCT priceBase , departureDate , arlineCompanyShortName , orgCityName,dstCityName , discount FROM flightinfo AS A WHERE EXISTS (SELECT orgCityName,dstCityName,departureDate FROM flightinfo AS B WHERE A.orgCityName=B.orgCityName and A.dstCityName=B.dstCityName and A.departureDate=B.departureDate) ORDER BY   `departureDate`,`priceBase` ;";
        dbc.sql(sql,function(res){
            console.log(res);

            for(var result in res){
                // console.log(res[result]);
                contexts[contexts.length]={text:JSON.stringify(res[result])}
            }
        });
    })
}
